<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="cart-page">
    <!-- 头部区域 -->
    <header class="cart-header">
      <div class="header-content">
        <h1 class="cart-title">购物车</h1>
        <div class="location-info">
          <van-icon name="location-o" class="location-icon" />
          <span class="location-text" @click="onClickLocation">{{locationStore.defaultAddressText}}</span>
          <van-icon name="arrow" class="location-arrow" />
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="cart-main">
      <div class="cart-content">
        <!-- 购物车列表 -->
        <div class="cart-list-section" :class="{ 'flex-1': cartList.length > 0 }">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            class="cart-list"
          >
            <div>
              <CartListItem 
                v-for="item in cartList" 
                :key="item.id" 
                :data="item"
                @confirm-change="handleConfirmChange"
                @quantity-change="handleQuantityChange"
                class="cart-item"
              />
            </div>
          </van-list>
          
          <!-- 空状态提示 -->
          <div v-if="cartList.length === 0 && !loading" class="empty-state">
            <van-empty 
              description="购物车是空的" 
              class="empty-cart"
              image-size="160"
            >
              <template #description>
                <div class="empty-description">
                  <p class="empty-title">购物车是空的</p>
                  <p class="empty-subtitle">快去添加一些美食吧～</p>
                </div>
              </template>
            </van-empty>
          </div>
        </div>

        <!-- 购物车统计信息 -->
        <div v-if="cartList.length > 0" class="cart-stats">
          <div class="stats-item">
            <span class="stats-label">商品总数：</span>
            <span class="stats-value">{{ totalItemsCount }} 件</span>
          </div>
          <div class="stats-item">
            <span class="stats-label">已选择：</span>
            <span class="stats-value">{{ confirmedItemsCount }} 件</span>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部操作栏 -->
    <div class="cart-footer">
      <van-submit-bar 
        :price="confirmedTotalPrice" 
        button-color="#ffc400" 
        button-text="提交订单" 
        @submit="onSubmit"
        :disabled="confirmedCart.length === 0"
        class="submit-bar"
      >
        <template #default>
          <div class="submit-bar-content">
            <!-- 全选框 -->
            <van-checkbox 
              v-model="selectAll" 
              checked-color="#ee0a24"
              @change="handleSelectAllChange"
              :disabled="cartList.length === 0"
              class="select-all-checkbox"
            >
              全选
            </van-checkbox>
            <div class="delete-section" @click="handleDelete">
              <van-icon name="delete" class="delete-icon" />
              <span class="delete-text">删除</span>
            </div>
          </div>
        </template>
        <template #tip>
          <div class="submit-tip">
            <van-icon name="info-o" class="tip-icon" />
            <span class="tip-text">合理的饮食搭配有益身体健康</span>
          </div>
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script setup>
import { useLocationStore } from '../../store/location'
import { useCartStore } from '../../store/cart'
import CartListItem from '../../components/CartListItem.vue'
import { reactive, ref, computed, watch } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import router from '@router'
import { useOrderStore } from '../../store/order'
defineOptions({
    name: 'CartIndex'
})
const locationStore = useLocationStore()
const orderStore = useOrderStore()
const cartStore = useCartStore()
// 购物车列表
const cartList = reactive([])
const loading = ref(false)
const finished = ref(false)
const selectAll = ref(false)
const onClickLocation = () => {
  router.push({ name: 'LocationList' })
}
// 计算已确认的商品
const confirmedCart = computed(() => cartList.filter(item => item.isConfirmed))

// 计算商品总件数（所有商品的数量总和）
const totalItemsCount = computed(() => {
  return cartList.reduce((total, item) => {
    return total + (item.num || 0)
  }, 0)
})

// 计算已确认的商品件数
const confirmedItemsCount = computed(() => {
  return confirmedCart.value.reduce((total, item) => {
    return total + (item.num || 0)
  }, 0)
})

// 计算已确认的总价（单位：元）
const confirmedTotalPrice = computed(() => {
  return confirmedCart.value.reduce((total, item) => {
    return total + (item.price * item.num)
  }, 0) * 100  // 转换为分，符合Vant SubmitBar的要求
})

// 监听购物车列表变化，更新全选状态
watch(() => cartList.length, () => {
  if (cartList.length === 0) {
    selectAll.value = false
  } else {
    selectAll.value = cartList.every(item => item.isConfirmed)
  }
}, { immediate: true })

// 处理商品确认状态变化
const handleConfirmChange = ({ item, confirmed }) => {
  if (!item || !item.id) return
  
  // 更新本地列表 - 创建新对象触发响应式更新
  const index = cartList.findIndex(cartItem => cartItem.id === item.id)
  if (index !== -1) {
    // 如果没找到的话 直接响应式的在数组末尾添加一个新对象
    cartList[index] = { ...cartList[index], isConfirmed: confirmed }
  }
  // 同步更新store中的状态
  cartStore.updateItemConfirmed(item, confirmed)
  
  // 更新全选状态  再次检查每一件商品是否被选中  
  selectAll.value = cartList.every(item => item.isConfirmed)
}

// 处理商品数量变化  与上方的逻辑一致
const handleQuantityChange = ({ item, quantity }) => {
  if (!item || !item.id || quantity < 1) return
  
  // 更新本地列表
  const targetItem = cartList.find(cartItem => cartItem.id === item.id)
  if (targetItem) {
    targetItem.num = quantity
  }
  // 同步更新store中的数量
  cartStore.updateItemNum(item.id, quantity)
}
// 全选状态变化
const handleSelectAllChange = (checked) => {
  // 更新本地列表 - 创建新对象触发响应式更新
  cartList.forEach((item, index) => {
    cartList[index] = { ...item, isConfirmed: checked }
  })
  // 同步更新store
  cartStore.toggleAllConfirmed(checked)
}
// 处理删除
const handleDelete = () => {
  const confirmedItems = confirmedCart.value
  if (confirmedItems.length === 0) {
    showToast('请先选择要删除的商品')
    return
  }
  
  showConfirmDialog({
    title: '删除确认',
    message: `确定要删除选中的${confirmedItems.length}件商品吗？`,
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonColor: '#ee0a24'
  })
  .then(() => {
    // 从store中删除已确认的商品
    confirmedItems.forEach(item => {
      cartStore.removeItemById(item.id)
    })
    
    // 从本地列表中删除 - 保留未确认的商品
    const unconfirmedItems = cartList.filter(item => !item.isConfirmed)
    cartList.splice(0, cartList.length, ...unconfirmedItems)
    
    showToast('删除成功')
    selectAll.value = false
  })
  .catch(() => {
    // 取消删除
  })
}

// 提交订单
const onSubmit = () => {
  if (confirmedCart.value.length === 0) {
    showToast('请先选择商品')
    return
  }

  showToast(`提交订单成功！共${confirmedItemsCount.value}件商品，总价：${(confirmedTotalPrice.value / 100).toFixed(2)}元`)
  
  // 先保存数据到orderStore，再移除购物车数据！
  Object.assign(orderStore.tempPaymentList, confirmedCart.value)
  
  // 从购物车store中移除已确认的商品 - 注意：这一步要在数据传递之后！
  cartStore.removeConfirmedItems()
  
  // 更新本地购物车列表 - 保留未确认的商品
  const unconfirmedItems = cartList.filter(item => !item.isConfirmed)
  cartList.splice(0, cartList.length, ...unconfirmedItems)
  
  // 重置全选状态
  selectAll.value = false
  
  // 跳转到创建订单页
  router.push('/payment')
}
const onLoad = () => { 
  loading.value = true
  // 模拟使用axios了 以后使用等我写出接口的时候再使用axios
  setTimeout(() => { 
    try {
      // 获取购物车中的数据  
      const storeCartList = cartStore.cartList || []
      if (storeCartList && storeCartList.length > 0) {
        // 清空现有列表并添加新数据
        cartList.splice(0, cartList.length)
        storeCartList.forEach(item => {
          cartList.push({
            ...item,
            isConfirmed: item.isConfirmed || false
          })
        })
      }
      loading.value = false
      finished.value = true
    } catch (error) {
      console.error('加载购物车数据失败:', error)
      loading.value = false
      finished.value = true
    }
  }, 500)
}
</script>

<style lang="scss" scoped>
.cart-page {
  min-height: 100vh;
  background: #f6f6f6;
  display: flex;
  flex-direction: column;

  .cart-header {
    background: #fff;
    padding: 12px 16px;
    border-bottom: 1px solid #ebedf0;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .cart-title {
        font-size: 18px;
        font-weight: 600;
        color: #323233;
      }

      .location-info {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #969799;

        .location-icon {
          margin-right: 4px;
        }

        .location-text {
          margin-right: 4px;
        }

        .location-arrow {
          font-size: 12px;
        }
      }
    }
  }

  .cart-main {
    flex: 1;
    padding: 12px;

    .cart-content {
      background: #fff;
      border-radius: 8px;
      overflow: hidden;

      .cart-list-section {
        &.flex-1 {
          flex: 1;
        }

        .cart-list {

          .cart-item {
            border-bottom: 1px solid #f5f5f5;
          }
        }

        .empty-state {
          padding: 40px 0;

          .empty-cart {
            .empty-description {
              text-align: center;
              .empty-title {
                font-size: 16px;
                color: #323233;
                margin-bottom: 8px;
              }

              .empty-subtitle {
                font-size: 14px;
                color: #969799;
              }
            }
          }
        }
      }

      .cart-stats {
        padding: 12px 16px;
        border-top: 1px solid #f5f5f5;
        display: flex;
        justify-content: space-between;
        background: #fafafa;

        .stats-item {
          font-size: 14px;

          .stats-label {
            color: #969799;
          }

          .stats-value {
            color: #ff9900;
            font-weight: 500;
          }
        }
      }
    }
  }

  .cart-footer {
    background: #fff;
    border-top: 1px solid #ebedf0;

    .submit-bar {
      position: relative;
      .submit-bar-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;

        .select-all-checkbox {
          font-size: 14px;
        }

        .delete-section {
          display: flex;
          align-items: center;
          margin-left: 16px;
          color: #969799;
          font-size: 14px;

          .delete-icon {
            margin-right: 4px;
          }
        }
      }

      .submit-tip {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #969799;
        padding: 8px 16px;
        background: #fff9ed;

        .tip-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
<style scoped lang="scss"> 


</style>